package com.ruoyi.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.UserDataIsolation;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.domain.ProductProperty;
import com.ruoyi.system.domain.ProductPropertyValue;
import com.ruoyi.system.domain.vo.ProductPropertyValueResultVO;
import com.ruoyi.system.domain.vo.ProductPropertyValueVO;
import com.ruoyi.system.mapper.ProductPropertyValueMapper;
import com.ruoyi.system.service.IProductPropertyService;
import com.ruoyi.system.service.IProductPropertyValueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Slf4j
@Service
public class ProductPropertyValueServiceImpl implements IProductPropertyValueService {
    @Autowired
    private ProductPropertyValueMapper productPropertyValueMapper;
    @Autowired
    private IProductPropertyService productPropertyService;

    @Override
    @UserDataIsolation(tableAlias = "t1")
    public List<ProductPropertyValueResultVO> queryProductPropertyValue(ProductPropertyValue productPropertyValue) {
        //查询所有的配置字段
        ProductProperty productProperty = new ProductProperty();
        productProperty.setId(productPropertyValue.getPropertyId());
        productProperty.setPropertyGroup(productPropertyValue.getPropertyGroup());
        List<ProductProperty> productProperties = productPropertyService.queryPageList(productProperty);
        if (CollectionUtils.isEmpty(productProperties)) {
            return new ArrayList<>();
        }
        List<ProductPropertyValueVO> result = new ArrayList<>();
        List<ProductPropertyValue> productPropertyValues = productPropertyValueMapper.queryProductValue(productPropertyValue);
        if (CollectionUtils.isEmpty(productPropertyValues)) {
            for (ProductProperty property : productProperties) {
                ProductPropertyValueVO valueVO = initValueVO(null, property, productPropertyValue.getProductId());
                if (valueVO != null) {
                    result.add(valueVO);
                }
            }
            return initResultVO(result);
        }
        //获取已赋值的属性
        for (ProductPropertyValue value : productPropertyValues) {
            for (ProductProperty property : productProperties) {
                if (value.getPropertyId().compareTo(property.getId()) == 0) {
                    ProductPropertyValueVO valueVO = initValueVO(value, property, productPropertyValue.getProductId());
                    if (valueVO != null) {
                        result.add(valueVO);
                    }
                    break;
                }
            }
        }
        //获取未赋值的属性
        Set<Integer> propertyIds = productPropertyValues.stream().map(ProductPropertyValue::getPropertyId).collect(Collectors.toSet());
        productProperties.stream().forEach(a -> {
            if (!propertyIds.contains(a.getId())) {
                ProductPropertyValueVO valueVO = initValueVO(null, a, productPropertyValue.getProductId());
                if (valueVO != null) {
                    result.add(valueVO);
                }
            }
        });
        return initResultVO(result);
    }

    /**
     * 获取产品额外属性值结果
     *
     * @param productPropertyValueVOS
     * @return
     */
    private List<ProductPropertyValueResultVO> initResultVO(List<ProductPropertyValueVO> productPropertyValueVOS) {
        if (CollectionUtils.isEmpty(productPropertyValueVOS)) {
            return new ArrayList<>();
        }
        Map<String, List<ProductPropertyValueVO>> listMap = productPropertyValueVOS.stream().collect(Collectors.groupingBy(ProductPropertyValueVO::getPropertyGroup));
        List<ProductPropertyValueResultVO> resultVOS = new ArrayList<>();
        for (Map.Entry<String, List<ProductPropertyValueVO>> entry : listMap.entrySet()) {
            ProductPropertyValueResultVO resultVO = new ProductPropertyValueResultVO();
            resultVO.setPropertyGroup(entry.getKey());
            List<ProductPropertyValueVO> value = entry.getValue();
            Collections.sort(value, new Comparator<ProductPropertyValueVO>() {
                @Override
                public int compare(ProductPropertyValueVO o1, ProductPropertyValueVO o2) {
                    return o1.getOrderNum() - o2.getOrderNum();
                }
            });
            resultVO.setProductPropertyValueVOS(value);
            resultVOS.add(resultVO);
        }
        return resultVOS;
    }

    @Override
    @Transactional
    public Boolean saveOrUpdate(List<ProductPropertyValue> productPropertyValues, String userName, Long companyId) {
        productPropertyValues.forEach(a -> {
            if (a.getProductId() == null || a.getPropertyId() == null) {
                throw new CustomException("产品id或属性id不能为空");
            }
        });
        //获取需要修改的属性
        List<ProductPropertyValue> updateProductList = productPropertyValues.stream().filter(a -> !StringUtils.isEmpty(a.getId())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(updateProductList)) {
            for (ProductPropertyValue value : updateProductList) {
                productPropertyValueMapper.updateProductProperty(value);
            }
        }
        //获取需要新增的属性
        List<ProductPropertyValue> saveProductList = productPropertyValues.stream().filter(a -> StringUtils.isEmpty(a.getId()) && !StringUtils.isEmpty(a.getValue())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(saveProductList)) {
            for (ProductPropertyValue value : saveProductList) {
                value.setCompanyId(companyId);
                value.setCreateBy(userName);
                value.setCreateTime(new Date());
                productPropertyValueMapper.saveProductProperty(value);
            }
        }
        return true;
    }

    @Override
    @UserDataIsolation
    public Boolean deleteProductPropertyValue(ProductPropertyValue productPropertyValue) {
        return productPropertyValueMapper.deleteProductPropertyValue(productPropertyValue) > 0;
    }

    @Override
    @UserDataIsolation(tableAlias = "t1")
    public List<ProductPropertyValueVO> getProductValue(ProductPropertyValueVO productPropertyValueVO) {
        if (productPropertyValueVO == null || productPropertyValueVO.getPropertyId() == null){
            throw new CustomException("属性值不能为空");
        }
        List<ProductPropertyValueVO> productValue = productPropertyValueMapper.getProductValue(productPropertyValueVO);
        if (CollectionUtils.isEmpty(productValue)){
            return new ArrayList<>();
        }
        List<ProductPropertyValueVO> collect = productValue.stream().filter(a -> StrUtil.isNotBlank(a.getValue())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)){
            return new ArrayList<>();
        }
        return collect;
    }

    /**
     * 获取产品属性值VO
     *
     * @param value
     * @param property
     * @param productId
     * @return
     */
    private ProductPropertyValueVO initValueVO(ProductPropertyValue value, ProductProperty property, Integer productId) {
        if (property == null) {
            return null;
        }
        ProductPropertyValueVO valueVO = new ProductPropertyValueVO();
        valueVO.setDataType(property.getDataType());
        if (value != null) {
            valueVO.setValue(value.getValue());
            valueVO.setId(value.getId());
        }
        valueVO.setProductId(productId);
        valueVO.setOrderNum(property.getOrderNum());
        valueVO.setPropertyGroup(property.getPropertyGroup());
        valueVO.setPropertyId(property.getId());
        valueVO.setPropertyName(property.getPropertyName());
        return valueVO;
    }
}
